<template>
  <div class="default-main ba-table-box">
    <div class="block">
      <div class="table-block">
        <el-alert class="ba-table-alert"
                  v-if="baTable.table.remark"
                  :title="baTable.table.remark"
                  type="info"
                  show-icon />
        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                     :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
          <template #month>
            <el-date-picker v-model="baTable.comSearch.form['date']"
                            type="month"
                            placeholder="选择月份"
                            value-format="YYYY-MM" />
          </template>
          <template #shop>
            <el-select filterable
                       v-model="baTable.comSearch.form['shop_id']"
                       clearable>
              <el-option v-for="item in shop_arr"
                         :key="item.shop_id"
                         :label="item.shop_name"
                         :value="item.shop_id">
              </el-option>
            </el-select>
          </template>
        </TableHeader>
        <el-row style="margin: 10px 0;"
                :gutter="10">
          <el-col :span="1.5"
                  v-if="baTable.auth('export')">
            <el-button type="warning"
                       @click="exportExcelOperate"
                       :loading="state.buttonLoading">
              <Icon color="#ffffff"
                    name="el-icon-Position" />导出
            </el-button>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName"
                 class="demo-tabs table-header ba-scroll-style"
                 @tab-click="handleStatus"
                 type="border-card">
          <el-tab-pane label="云汇回款"
                       name="USD"></el-tab-pane>
          <el-tab-pane label="连连回款"
                       name="CNH"></el-tab-pane>
        </el-tabs>
        <Table show-summary
               :summary-method="getSummaries"></Table>
      </div>
    </div>
    <DetailCom ref="detailCom"
               :curRow="curRow" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, provide, onBeforeMount } from 'vue'
import { ElMessageBox, TabsPaneContext } from 'element-plus'
import baTableClass from '/@/utils/baTable'
// import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import DetailCom from './detailCom.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi, fileDownload } from '/@/api/common'
import { useAdminInfo } from '/@/stores/adminInfo'
import Cookies from 'js-cookie'
import { useI18n } from 'vue-i18n'
import { concat } from 'lodash-es'
import { getShopList } from '/@/api/backend/common'
import { exportExcel } from '/@/api/backend/checkbill/paymentCollection'

defineOptions({
    name: 'checkbill/paymentCollection',
})
const { t } = useI18n()
const activeName = ref('USD')
const detailCom: any = ref<InstanceType<typeof DetailCom>>()
const curRow = ref({})
const shop_arr = ref([] as any[])
const state: {
    buttonLoading: boolean
} = reactive({
    buttonLoading: false
})
const adminInfo = useAdminInfo()
let optButtons: OptButton[] = [
    {
        render: 'tipButton',
        name: 'info',
        title: 'Info',
        text:  '详情',
        type: 'primary',
        icon: '',
        class: 'newButton',
        disabledTip: false,
        click: (row: TableRow) => {
            curRow.value = { ...row }
            detailCom.value.show = true
        }
    }
]
optButtons = concat(defaultOptButtons(['edit', 'delete']), optButtons)
optButtons[1].display = (row) => {
    return row.id != adminInfo.id
}
const handleStatus = (tab: TabsPaneContext) => {
    // baTable.filter = {'status': tab.props.name}
    baTable.comSearch.form['status'] = tab.props.name
    const comSearchData: Array<any> = baTable.table.filter?.search || [];
    comSearchData.push({
        field: "status",
        val: tab.props.name,
        operator: "",
        render: "",
    })
    baTable.onTableAction('com-search', comSearchData)
}
const baTable = new baTableClass(
    new baTableApi('/checkbill/paymentCollection/'),
    {
        column: [
            {
                label: '月份',
                prop:  'date',
                operator: '=', 
                align: 'center',
                comSearchRender:'slot',
                comSearchSlotName: 'month',
            },
            {
                label: '店铺',
                prop:  'shop_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                comSearchSlotName: 'shop',
                show: false
            },
            {   
                label: '店铺',
                prop: 'shop_name', 
                align: 'center',
                operator: false,
                width: 150
            },
            {   
                label: '银行账号', 
                prop: 'bank_account', 
                align: 'center',
                operator: false
            },
            {   
                label: '结算金额', 
                prop: 'settlement_amount', 
                align: 'center',
                operator: false
            },
            {   
                label: '储备金额', 
                prop: 'reserve_amount', 
                align: 'center',
                operator: false
            },
            {   
                label: '付款金额', 
                prop: 'amount', 
                align: 'center',
                operator: false
            },
            {   
                label: '币种', 
                prop: 'currency', 
                align: 'center',
                operator: false
            },
            {   
                label: '支付状态', 
                prop: 'pay_status', 
                align: 'center',
                operator: false,
                render: 'tag'
            },
            { 
                label: '付款时间', 
                prop: 'paid_time',
                align: 'center',
                render: 'datetime',
                sortable: 'custom', 
                operator: 'RANGE', 
                width: 160
            },
            // {
            //     label: t('Operate'),
            //     align: 'center',
            //     width: '100',
            //     render: 'buttons',
            //     buttons: optButtons,
            //     operator: false
            // }
        ],
        dblClickNotEditColumn: ['all'],
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()
const getSummaries = (param:any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column:any, index:any) => {
    const key = column.columnKey
    switch(key){
        case 'amount':
            sums[index] = baTable.table.extend?.total_amount
            break
        default:
            sums[index] = ''
    }
  })
  return sums
}
const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
        state.buttonLoading = false
        baTable.table.loading = false
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}
const getShopArr = () => {
    getShopList().then(res => {
        if(res.data && res.data.list.length) {
            shop_arr.value = res.data.list
        }
    })
}

onBeforeMount(() => {
    getShopArr()
})
</script>

<style scoped lang="scss">
:deep(.el-date-editor.el-input){
    width: var(--el-input-width);
}
</style>
